package com.abso.mp3tunes.locker.ui.actions;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.eclipse.core.runtime.IProgressMonitor;

import com.abso.mp3tunes.locker.core.data.Track;
import com.abso.mp3tunes.locker.ui.LockerImages;
import com.abso.mp3tunes.locker.ui.viewers.LockerViewer;

/**
 * Action able to export a XSPF playlist.
 */
public class ExportXSPFPlaylistAction extends AbstractExportPlaylistAction {

	/** The XSPF namespace URI. */
	private static final String XSPF_NS_URI = "http://xspf.org/ns/0/";

	/**
	 * Constructs a new action.
	 * 
	 * @param lockerViewer
	 *            the Locker tree viewer.
	 */
	public ExportXSPFPlaylistAction(LockerViewer lockerViewer) {
		super("XSPF", LockerImages.getDescriptor(LockerImages.XSPF), lockerViewer);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#getFileFilterExtensions()
	 */
	protected String[] getFileFilterExtensions() {
		return new String[] { "*.xspf" };
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#getFileEncoding()
	 */
	protected String getFileEncoding() {
		return "UTF-8";
	}

	/* (non-Javadoc)
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#getPlaylistPath(java.lang.String)
	 */
	protected String getPlaylistPath(String filePath) {
		String playlistPath = filePath;
		if (!playlistPath.toLowerCase().endsWith(".xspf")) {
			return playlistPath + ".xspf";
		} else {
			return playlistPath;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#exportTracks(com.abso.mp3tunes.locker.core.data.Track[],
	 *      java.io.PrintWriter, org.eclipse.core.runtime.IProgressMonitor)
	 */
	protected void exportTracks(Track[] tracks, PrintWriter writer,
			IProgressMonitor monitor) throws IOException {
		Document doc = DocumentHelper.createDocument();
		Element playlist = doc.addElement(QName.get("playlist", "", XSPF_NS_URI)).addAttribute("version", "1");
		playlist.addElement(QName.get("title", "", XSPF_NS_URI)).setText("MP3tunes Locker");
		playlist.addElement(QName.get("creator", "", XSPF_NS_URI)).setText("MP3tunes Locker Eclipse Plug-In (http://abso.freehostia.com/mp3tunes)");
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(new Date(System.currentTimeMillis()));
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
		dateFormat.setTimeZone(calendar.getTimeZone());
		StringBuffer date = new StringBuffer(dateFormat.format(calendar.getTime()));
		date.insert(date.length() - 2, ':');
		playlist.addElement(QName.get("date", "", XSPF_NS_URI)).setText(date.toString());	
		Element trackList = playlist.addElement(QName.get("trackList", "", XSPF_NS_URI));
		for (int i = 0; i < tracks.length; i++) {
			if (monitor.isCanceled()) {
				break;
			}
			Element track = trackList.addElement(QName.get("track", "", XSPF_NS_URI));
			track.addElement(QName.get("location", "", XSPF_NS_URI)).setText(tracks[i].getPlayURL());
			track.addElement(QName.get("title", "", XSPF_NS_URI)).setText(tracks[i].getTitle());
			track.addElement(QName.get("creator", "", XSPF_NS_URI)).setText(tracks[i].getArtistName());
			track.addElement(QName.get("image", "", XSPF_NS_URI)).setText(tracks[i].getAlbumArtURL());
			track.addElement(QName.get("album", "", XSPF_NS_URI)).setText(tracks[i].getAlbumTitle());
			if (tracks[i].getNumber() > 0) {
				track.addElement(QName.get("trackNum", "", XSPF_NS_URI)).setText(String.valueOf(tracks[i].getNumber()));
			}
			int duration = (int) tracks[i].getLength();
			if (duration > 0) {
				track.addElement(QName.get("duration", "", XSPF_NS_URI)).setText(String.valueOf(duration));
			}
			
			
			
			monitor.worked(1);
		}
		
//		Element asx = doc.addElement("ASX").addAttribute("VERSION", "3.0");
//		asx.addText(SystemUtils.LINE_SEPARATOR);
//		asx.addElement("PARAM").addAttribute("NAME", "Encoding").addAttribute("VALUE", "utf-8");
//		asx.addText(SystemUtils.LINE_SEPARATOR);
//		asx.addElement("TITLE").setText("MP3tunes Locker");
//		asx.addText(SystemUtils.LINE_SEPARATOR);
//		for (int i = 0; i < tracks.length; i++) {
//			if (monitor.isCanceled()) {
//				break;
//			}
//			Element entry = asx.addElement("ENTRY");
//			entry.addElement("REF").addAttribute("HREF", tracks[i].getPlayURL());
//			entry.addElement("TITLE").setText(tracks[i].getArtistName() + " - " + tracks[i].getAlbumTitle() + " - " + tracks[i].getTitle());
//			asx.addText(SystemUtils.LINE_SEPARATOR);
//			monitor.worked(1);
//		}
        OutputFormat outFormat = new OutputFormat();
        outFormat.setSuppressDeclaration(false);
        outFormat.setNewLineAfterDeclaration(false);
        outFormat.setIndent(true);
        outFormat.setNewlines(true);
        outFormat.setTrimText(false);
        outFormat.setPadText(false);
        outFormat.setEncoding("UTF-8");
        XMLWriter xmlWriter = new XMLWriter(writer, outFormat);
        xmlWriter.setMaximumAllowedCharacter(127);
        xmlWriter.write(doc);
        xmlWriter.flush();
        xmlWriter.close();
	}

}
